import {
  reqGetAttrCategory1,
  reqGetAttrCategory2,
  reqGetAttrCategory3,
  reqGetAttrInfoList,
  reqAttrsaveAttrInfo
} from '@/api/attr'

const getDefaultState = () => {
  return {
    category1Id: null,
    category2Id: null,
    category3Id: null,
    category1List: [
      {
        id: null,
        name: ''
      }
    ],
    category2List: [
      {
        id: null,
        name: '',
        category1Id: null
      }
    ],
    category3List: [
      {
        id: null,
        name: '',
        category2Id: null
      }
    ],
    attrInfoList: [
      // {
      //   id: null,
      //   attrName: '',
      //   categoryId: null,
      //   categoryLevel: null,
      //   attrValueList: [
      //     {
      //       id: null,
      //       valueName: '',
      //       attrId: null
      //     }
      //   ]
      // }
    ],
    attrRow: {}
  }
}

const state = getDefaultState()

const mutations = {
  SETCATEGORY1LIST: (state, data) => {
    state.category1List = data
  },
  SETCATEGORY2LIST: (state, data) => {
    state.category2List = data
  },
  SETCATEGORY3LIST: (state, data) => {
    state.category3List = data
  },
  SETATTRINFOLIST: (state, data) => {
    state.attrInfoList = data
  },
  SETCATEGORY1ID: (state, id) => {
    state.category1Id = id
  },
  SETCATEGORY2ID: (state, id) => {
    state.category2Id = id
  },
  SETCATEGORY3ID: (state, id) => {
    state.category3Id = id
  },
  CLEARATTRINFOLIST: state => {
    state.attrInfoList = []
  },
  SETATTRROW: (state, attr) => {
    state.attrRow = attr
  }
}
const actions = {
  async getCategory1List({ commit }) {
    const result = await reqGetAttrCategory1()
    if (result.code !== 200) return
    commit('SETCATEGORY1LIST', result.data)
  },
  async getCategory2List({ commit, state }) {
    const result = await reqGetAttrCategory2(state.category1Id)
    if (result.code !== 200) return
    commit('SETCATEGORY2LIST', result.data)
  },
  async getCategory3List({ commit, state }) {
    const result = await reqGetAttrCategory3(state.category2Id)
    if (result.code !== 200) return
    commit('SETCATEGORY3LIST', result.data)
  },
  async getAttrInfoList({ commit, state }) {
    const { category1Id, category2Id, category3Id } = state
    const result = await reqGetAttrInfoList(category1Id, category2Id, category3Id)
    if (result.code !== 200) return
    commit('SETATTRINFOLIST', result.data)
  },
  async addAttr({ commit }, obj) {
    const result = await reqAttrsaveAttrInfo(obj)
    if (result.code == 200) {
      return Promise.resolve()
    } else {
      return Promise.reject('添加属性失败!!')
    }
  },
  setAttrRow({ commit }, attr) {
    commit('SETATTRROW', attr)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
